<template>
  <div class="app-container">
      <div class="title-wrapper">项目付款管理</div>
      <div class="page-main">
      <div shadow="never" class="search-wrapper" v-permission="['project-payment-search']">
        <div class="search-main">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="name" label="项目名称">
              <el-input v-model="searchData.name" placeholder="请输入项目名称" clearable/>
            </el-form-item>
            <el-form-item prop="payTime" label="付款日期">
              <el-date-picker
                v-model="searchData.payTime"
                type="date"
                placeholder="请选择"
                style="width:100%;"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item prop="requestPayTime" label="请款日期">
              <el-date-picker
                v-model="searchData.requestPayTime"
                type="date"
                placeholder="请选择"
                style="width:100%;"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item prop="startShootingTime" label="开票日期">
              <el-date-picker
                v-model="searchData.startShootingTime"
                type="date"
                placeholder="请选择"
                style="width:100%;"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item prop="contractName" label="合同名称">
              <el-input v-model="searchData.contractName" placeholder="请输入合同名称" clearable/>
            </el-form-item>
            <!-- <el-form-item prop="sortType" label="排序">
              <el-select v-model="searchData.sortType" style="width:150px" placeholder="请选择">
                <el-option label="所属月升序" value="1"></el-option>
                <el-option label="所属月降序" value="2"></el-option>
              </el-select>
            </el-form-item> -->

          </el-form>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
      <div class="toolbar-wrapper">
          <el-upload v-permission="['project-payment-add']" action="#" class="upload-demo" accept=".xlsx, .xls" :on-exceed="exceedFile" :on-error="handleError"
          :on-success="handleSuccess" :http-request="uploadExcel" :before-upload="beforeUPload" :show-file-list="true"
          :limit="1">
          <el-button type="primary">导入</el-button>
        </el-upload>

          <el-button style="margin-left:10px;" type="primary" v-permission="['project-payment-download']" @click="handleExport({}, '/bg/projectPayRecord/downloadImportTemplate','项目付款模板')">下载导入模版</el-button>
      </div>

      <div v-loading="loading"  class="table-wrapper">
        <el-table :data="tableData" @sort-change="handleSortChange">
          <el-table-column prop="projectSeq" label="序号" width="60"  />
          <el-table-column prop="projectName" label="项目名称"  />
          <el-table-column prop="month" label="费用所属月" sortable="custom" width="120"  />
          <el-table-column prop="requestPayPrice" label="请款金额" sortable="custom">
            <template #default="scope">
              {{ scope.row.requestPayPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="requestPayTime" label="请款日期" sortable="custom" width="120">
            <template #default="scope">
              {{ scope.row.requestPayTime }}
            </template>
          </el-table-column>

          <el-table-column prop="startShootingPrice" label="开票金额"  sortable="custom">
            <template #default="scope">
              <div style="color:#fcc408">{{ scope.row.startShootingPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="startShootingTime" label="开票日期"  sortable="custom" width="120">
            <template #default="scope">
              <div style="color:#fcc408">{{ scope.row.startShootingTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="payPrice" label="付款金额"  sortable="custom">
            <template #default="scope">
              <div style="color:#f00">{{ scope.row.payPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="payTime" label="付款日期" sortable="custom" width="120">
            <template #default="scope">
              <div style="color:#f00">{{ scope.row.payTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="contractName" label="合同名称"  />


          <el-table-column fixed="right" label="操作" width="150" >
            <template #default="scope">
              <el-button type="primary" v-permission="['project-payment-edit']" text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" v-permission="['project-payment-del']" text size="small" @click="handleDetils(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <gm-dialog v-if="dialogVisible"
    ref="dialogRef"
    title="新增/编辑项目付款"
    @cancel="closeHandle"
    @comfirm="successHandle">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item prop="month" label="费用所属月">
        <el-date-picker
          v-model="form.month"
          type="month"
          format="YYYY-MM" value-format="YYYY-MM"
          placeholder="请选择"
        />
      </el-form-item>
      <el-form-item prop="requestPayPrice" label="请款金额">
        <el-input v-model="form.requestPayPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="requestPayTime" label="请款日期">
        <el-date-picker
          v-model="form.requestPayTime"
          type="date"
          placeholder="请选择"
          style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item prop="startShootingPrice" label="开票金额">
        <el-input v-model="form.startShootingPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="startShootingTime" label="开票日期">
        <el-date-picker
          v-model="form.startShootingTime"
          type="date"
          placeholder="请选择"
          style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item prop="payPrice" label="付款金额">
        <el-input v-model="form.payPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item  prop="payTime" label="付款日期">
        <el-date-picker
          v-model="form.payTime"
           style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
          placeholder="请选择"
        />
      </el-form-item>



    </el-form>
  </gm-dialog>
  <handledetails
    v-if="dialogDetailsVisible"
    :title="'项目付款详情'"
    :data="activeRow"
    @success="successHandle1"
    @cancel="closeHandle1"
    />
</template>
<script lang="ts" setup>
  import { ref, watch,reactive,nextTick } from "vue"
    import { request } from "@/utils/service"
  import { type FormInstance, ElMessage, ElMessageBox,type FormRules } from "element-plus"
  import { getProjectPayRecordList,saveOrUpdateProjectPayRecord,getProjectPayRecordById,downloadImportTemplate } from "@/api/projectPayRecord"
  import { usePagination1 } from "@/hooks/usePagination"
  import useTable from '@/hooks/useTable'
  import gmDialog from '@/components/Dialog/index.vue'
  import useForm from '@/hooks/useForm'
  import { cloneDeep } from "lodash-es"
  import useFile from '@/hooks/useFile'
  import handledetails from './components/handledetails.vue'


  const activeRow = ref<any>()

  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination1()
  const tableData = ref<any>([])
  const dialogVisible = ref<boolean>(false)
  const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({})

  const form = ref<any>({})
  const formRef = ref<FormInstance>()
  const dialogRef = ref<InstanceType<typeof gmDialog>>()

  const { beforeUpload, uploadUrl, uploadImage } = useFile({ maxSize: 10, fileType: 'image' })


  const dialogDetailsVisible = ref<boolean>(false)


  const rules: FormRules = {
    month: [
      { required: true, message: '请选择费用所属月', trigger: 'change' },
    ],
  }



  const getTableData = () => {
    loading.value = true
    getProjectPayRecordList({
      ...paginationData,
      ...searchData,
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }


const handleSortChange = (data:any) => {
  console.log(data, 'data')
  // 在方法触发时先获取并保存接口需要的字段,调用分页方法,分页方法中掉用了获取列表数据方法
  // data.order为空时仅刷新页面'
  searchData.requestPayTimeSort = '';
  searchData.payPriceSort = '';
  searchData.payTimeSort = '';
  searchData.monthSortTypeSort = '';
  searchData.requestPayPriceSort = '';
  searchData.startShootingPriceSort = '';
  searchData.startShootingTimeSort = '';
  if (data.order === null) {
    searchData.sortType = '' // 数量1排序方式 1从大到小 2从小到大
    // Reset sorting fields
    searchData.requestPayTimeSort = '';
    searchData.payPriceSort = '';
    searchData.payTimeSort = '';
    searchData.monthSortTypeSort = '';
    searchData.requestPayPriceSort = '';
    searchData.startShootingPriceSort = '';
    searchData.startShootingTimeSort = '';
    handleSearch() // 查询方式
    return
  }

  // 根据colume.prop判断是哪一列(点击的当前是哪一列)
  if (data.prop === "requestPayTime") {
    // 请款日期
    searchData.requestPayTimeSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "payPrice") {
    // payPriceSort	付款金额是否升序
    searchData.payPriceSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "payTime") {
    // payTimeSort	付款日期是否升序
    searchData.payTimeSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "month") {
    // monthSortTypeSort	所属月是否升序
    searchData.monthSortTypeSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "requestPayPrice") {
    // requestPayPriceSort	请款金额是否升序
    searchData.requestPayPriceSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "startShootingPrice") {
    // startShootingPriceSort	开票金额 是否升序
    searchData.startShootingPriceSort = (data.order === 'ascending') ? true : false;
  } else if (data.prop === "startShootingTime") {
    // startShootingTimeSort	开票日期 是否升序
    searchData.startShootingTimeSort = (data.order === 'ascending') ? true : false;
  }

  handleSearch() // 调用查询方法
}

  const { handleSelectionChange,handleoneDelete,handleExport } = useTable({getList:getTableData})

  const handleUpdate = (row: any) => {
    getProjectPayRecordById({id:row.projectPayRecordId}).then((res: any) => {
      console.log(res,'res')
      form.value = res
      nextTick(()=>{
        form.value.carId =res.carId
        form.value.pics = res.pic ? res.pic.split(',') : []
      })
      dialogVisible.value = true
    }).catch(() => {

    }).finally(() => {
      loading.value = false
    })

  }

  const handleAdd = () => {
    form.value = {
      pics:[]
    }
    dialogVisible.value = true
  }

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  //搜索操作
  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  //重置搜索表单
  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }

  //操作完成
  const successHandle = () => {
    form.value.pic = form.value.pics.join(',')
    let newForm={
      projectPayRecordId:form.value.projectPayRecordId,
      month: form.value.month ? form.value.month.substring(0, 7) : '', // Convert to yyyy-mm format
      payPrice:form.value.payPrice,
      payTime:form.value.payTime,
      requestPayPrice:form.value.requestPayPrice,
      requestPayTime:form.value.requestPayTime,
      startShootingPrice:form.value.startShootingPrice,
      startShootingTime:form.value.startShootingTime,

    }
    handleSubmit(saveOrUpdateProjectPayRecord, formRef.value, newForm, dialogRef.value)

  }
  const handleSubmit = async(api: any, formEl:any,  formData: any, gmRef:any = null) => {
    await formEl.validate((valid: any) => {
      if (!valid) {
        return
      }
      gmRef.setLoading(true)
      api(formData).then((res: any)=>{
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        dialogVisible.value = false
        getTableData()
        gmRef.setLoading(false)
      }).catch(()=>{
        gmRef.setLoading(false)
      })
    })
  }

  const handleChange = (e: any)=>{
    console.log(e,'eeeee')
    form.value.carNo=e.carNo
  }



// 查看详情

const handleDetils = (row: any) => {
    activeRow.value = row
    dialogDetailsVisible.value = true
  }
const successHandle1 =()=>{
  dialogDetailsVisible.value = false
}

const closeHandle1=()=>{
  dialogDetailsVisible.value = false
}
  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })



//上传文件之前先判断该文件是否是Excel文件
// 文件上传之前判断
const beforeUPload = (file: any) => {
	const isExcel =
		file.type === 'application/vnd.ms-excel' ||
		file.type ===
		'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
	const isLt2M = file.size / 1024 / 1024 < 20;
	if (!isExcel)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式！',
			type: 'warning',
		});
	if (!isLt2M)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件大小不能超过 20MB!',
			type: 'warning',
		});
	return isExcel && isLt2M;
};
// 文件数超出提示
const exceedFile = () => {
	ElMessage.warning('最多只能上传一个文件！');
};
// 上传错误提示
const handleError = () => {
	ElMessage.error('导入数据失败，请您重新上传！');
};

//上传成功提示
const handleSuccess = () => {
	ElMessage.success('导入数据成功！');
	getTableData(); // Refresh the list after successful upload
};
// 文件上传
const uploadExcel = async (param: any) => {
	let fileFormData = new FormData();
	fileFormData.append('file', param.file);
	//导入公用人事考勤数据
	await request({//这里的http就是普通的axios实例
		method: 'post',
		url: '/bg/projectPayRecord/importPayRecord',
		headers: { "Content-Type": "multipart/form-data" },
		data: fileFormData
	})
};
</script>
<style lang="scss" scoped>
:deep(.el-upload-list) {
  display: none;

}
</style>
